package entity.connector;

import entity.bean.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 *
 * @author 52571783
 */
public class UserConnector {

    public static User getUser(String id) {
        try {
            Connection con = ConnectionProvider.getCon();
            PreparedStatement ps = con.prepareStatement(
                    "SELECT * FROM users WHERE user_id = ?",
                    ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            ps.setString(1, id);
            ResultSet rs = ps.executeQuery();
            rs.next();
            // store data from result set to static data members
            User user;
            if (rs.getString("user_role").equals("member")) {
                user = new User(1);
            } else if (rs.getString("user_role").equals("officer")) {
                // check if the officer is logged in already
                if (rs.getBoolean("login")) {
                    return null;
                } else {
                    user = new User(2);
                }
            } else {
                user = new User(3);
            }
            user.setId(rs.getString("user_id"));
            user.setName(rs.getString("name"));
            user.setGender(rs.getString("gender").charAt(0));
            if (user.getRole() == 2) {
                changeStatus(user, true);
            }
            return user;
        } catch (Exception e) {
            return null;
        }
    }

    public static void changeStatus(User user, boolean loginStatus) {
        try {
            Connection con = ConnectionProvider.getCon();
            PreparedStatement ps = con.prepareStatement("UPDATE users SET login = ? WHERE user_id = ?");
            ps.setBoolean(1, loginStatus);
            ps.setString(2, user.getId());
            ps.executeUpdate();
        } catch (Exception e) {
        }
    }
}